package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author jirunze
 * @date 2025-10-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 报警过滤
     */
    @Override
    public void alertFilter() {
        //查询所有规则，进行非空判断
        Long count = lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .count();
        if (count == null || count == 0) {
            log.info("没有启用的报警规则");
            return;
        }

        //查询所有上报的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)) {
            log.info("没有上报的数据");
            return;
        }

        //上报数据标准化处理，合并所有上报数据的物模型
        List<DeviceData> allDeviceDataList = new ArrayList<>();
        for (Object value : values) {
            List<DeviceData> deviceDataList = JSONUtil.toList(value.toString(), DeviceData.class);
            allDeviceDataList.addAll(deviceDataList);
        }

        //遍历每个设备上报数据的物模型
        allDeviceDataList.forEach(this::alertFilter);
    }

    /**
     * 数据报警处理器
     * @param deviceData 每个设备的物模型上报数据
     */
    private void alertFilter(DeviceData deviceData) {
        //校验上报时间是否小于1分钟，如果大于1分钟，直接return
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }

        //准备当前上报产品物模型的规则(查询当前设备的规则)
        List<AlertRule> currentIotRule = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .list();
        //准备当前上报产品物模型的规则(查询所有设备的规则)
        List<AlertRule> allIotRule = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, -1)
                .list();
        //合并规则
        Collection<AlertRule> allRules = CollectionUtil.addAll(currentIotRule, allIotRule);

        if (CollUtil.isEmpty(allRules)) {
            return;
        }
        allRules.forEach(rule -> deviceDataAlarmHandler(rule, deviceData));
    }

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 规则校验逻辑
     * @param rule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule rule, DeviceData deviceData) {
        //第一层校验-判断当前时间是否在生效时间内
        String alertEffectivePeriod = rule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime beginTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);

        LocalTime now = LocalTime.now();
        if (now.isBefore(beginTime) || now.isAfter(endTime)) {
            //不在生效时间
            log.info("不在生效时间{},{}", rule.getId(), deviceData.getId());
            return;
        }

        //第二层校验-判断数据阈值（当前上报的数据，是否异常）
        String dataValue = deviceData.getDataValue();
        //获取规则中的阈值和运算符
        Double value = rule.getValue();
        String operator = rule.getOperator();//运算符 < , >=

        //定义Redis报警次数的Key
        String alertTriggerCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX +
                deviceData.getIotId()
                + ":" + deviceData.getFunctionId()
                + ":" + rule.getId();

        //比较值
        int compare = Double.compare(Double.parseDouble(dataValue), value);//如果相等，返回0，如果第一个数字大于第二个数字，返回大于0，如果第一个数字小于第二个数字，返回小于0
        if ((">=".equals(operator) && compare >= 0) || ("<".equals(operator) && compare < 0)) {
            //满足阈值条件（说明数据异常）
            log.info("满足阈值条件上报数据值{}, 运算符:{},规则值{}", dataValue, operator, value);
        } else {
            //不满足阈值条件（说明数据正常）
            //删除redis报警次数  key: iot:+产品id+功能+规则id  value: 1
            redisTemplate.delete(alertTriggerCountKey);
            return;
        }

        //第三层校验-判断沉默周期
        //拼接沉默周期Key
        String alertSilentKey = CacheConstants.ALERT_SILENT_PREFIX +
                deviceData.getIotId()
                + ":" + deviceData.getFunctionId()
                + ":" + rule.getId();
        //从redis中获取沉默周期
        String silentValue = redisTemplate.opsForValue().get(alertSilentKey);
        if (StrUtil.isNotEmpty(silentValue)) {
            log.info("当前设备{},功能{},规则{}处于沉默状态", deviceData.getIotId(), deviceData.getFunctionId(), rule.getId());
            return;
        }
        //第四层校验-判断持续周期
        String triggerCount = redisTemplate.opsForValue().get(alertTriggerCountKey);
        Integer count = StrUtil.isEmpty(triggerCount) ? 1 : Integer.parseInt(triggerCount) + 1;
        //获取持续周期
        Integer duration = rule.getDuration();
        if (ObjectUtil.notEqual(count, duration)) {
            log.info("当前设备{},功能{},规则{}持续周期未达到,当前是第{}个周期，需要达到{}个周期才会报警", deviceData.getIotId(), deviceData.getFunctionId(), rule.getId(), count, duration);
            //持续周期未达到
            redisTemplate.opsForValue().set(alertTriggerCountKey, count.toString());
            return;
        }

        //满足报警条件
        log.info("当前设备{},功能{},规则{}满足报警条件", deviceData.getIotId(), deviceData.getFunctionId(), rule.getId());
        //删除redis报警次数
        redisTemplate.delete(alertTriggerCountKey);

        //添加沉默周期
        redisTemplate.opsForValue().set(alertSilentKey, "1", rule.getAlertSilentPeriod(), TimeUnit.MINUTES);


        //查找报警通知人
        List<Long> userIds = new ArrayList<>();
        if (ObjectUtil.equals(rule.getAlertDataType(), 0)) {
            //老人异常数据，通知护理员
            if (deviceData.getLocationType() == 0) {
                //说明是随身设备，根据老人查找护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            } else if (deviceData.getLocationType() == 1 && deviceData.getPhysicalLocationType() == 2) {
                //说明是固定设备（床位），根据床位查找老人，再根据老人查找护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        } else {
            //设备异常数据，通知维修工
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }

        //不论什么数据类型，都要通知超级管理员
        List<Long> longs = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");

        userIds.addAll(longs);

        //对用户id去重
//        userIds = userIds.stream().distinct().collect(Collectors.toList());
        userIds = CollUtil.distinct(userIds);

        //保存报警数据
        insertAlertData(userIds, deviceData, rule);

    }

    @Autowired
    private IAlertDataService alertDataService;

    private void insertAlertData(List<Long> userIds, DeviceData deviceData, AlertRule rule) {
        List<AlertData> alertDataList = userIds.stream().map(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setId(null);
            alertData.setAlertRuleId(rule.getId());
            alertData.setType(rule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
            alertData.setAlertReason(alertReason);
            return alertData;
        }).collect(Collectors.toList());

        //批量保存报警数据
        alertDataService.saveBatch(alertDataList);
    }

}
